<?php
/**
 * Created by <xinxin.deng>.
 * Author: xinxin.deng
 * Date: 2018/3/13 14:12
 */

header('Content-Type: text/html; charset=utf-8');
error_reporting(E_ALL);
set_time_limit(0);
include_once dirname(dirname(dirname(dirname(dirname(__FILE__)))))."/common.php";
\ns_core\m_load::load("ns_core.m_config");
\ns_core\m_load::load("ns_model.message.message_queue");
\ns_core\m_load::load("ns_core.m_timer");
\ns_core\m_load::load_np("np_ftp.php");
\ns_core\m_load::load_np("np_xml2array.class.php");

class import extends \ns_model\message\message_queue
{
    public $str_source_id = '';//上游来源ID
    public $passive = true;//FTP主被动模式
    /**
     * 注入消息队列模板
     * @var unknown
     */
    public $arr_in_message = array(
        'base_info'=>array(
            'nns_message_time'=>'', //上游消息时间  年月日时分秒毫秒
            'nns_message_id'=>'',  //上游消息ID
            'nns_cp_id'=>'', //上游CP标示
            'nns_message_xml'=>'',  //上游原始的信息  可以为字符串 | xml | json 或则存放消息地址
            'nns_message_content'=>'',  //上游解析后的信息  可以为字符串 | xml | json  生成队列的基本信息
            'nns_action'=>'', //操作 行为
            'nns_type'=>'', //消息 类型
            'nns_name'=>'',  //消息名称
            'nns_package_id'=>'',  //包ID
            'nns_xmlurlqc'=>'', //广州电信悦ME MD5摘要
            'nns_encrypt'=>'', //广州电信悦ME 加密串
            'nns_content_number'=>'', //xml文件中包含的内容数量
        ), //基本信息（存储于nns_mgtvbk_message表中）
    );

    public function __construct()
    {
        $arr_dir = explode('|', str_replace(array ('/','\\'), '|', __DIR__));
        $this->str_source_id = array_pop($arr_dir);
        \m_config::get_dc();
        \m_config::write_message_receive_log("-----------消息接收开始-----------",$this->str_source_id);
    }

    public function import()
    {
        $arr_source_config = \m_config::_get_cp_info($this->str_source_id);
        if ($arr_source_config['ret'] != NS_CDS_SUCCE)
        {
            \m_config::write_message_receive_log("上游接收来源CDS未配置", $this->str_source_id);
            return $arr_source_config;
        }
        if (empty($arr_source_config['data_info']))
        {
            \m_config::write_message_receive_log("获取CP[".$this->str_source_id."]信息为空", $this->str_source_id);
            return \m_config::return_data(NS_CDS_FAIL,"获取CP[".$this->str_source_id."]信息为空");
        }

        if(!isset($arr_source_config['data_info']['nns_config']['message_ftp_import_enable']) || $arr_source_config['data_info']['nns_config']['message_ftp_import_enable'] != '1')
        {
            \m_config::write_message_receive_log("获取CP[".$this->str_source_id."]配置[message_ftp_import_enable]FTP消息注入开关关闭", $this->str_source_id);
            return \m_config::return_data(NS_CDS_FAIL,"获取CP[".$this->str_source_id."]配置[message_ftp_import_enable]FTP消息注入开关关闭");
        }
        if(!isset($arr_source_config['data_info']['nns_config']['message_ftp_import_file_url']) || empty($arr_source_config['data_info']['nns_config']['message_ftp_import_file_url']))
        {
            \m_config::write_message_receive_log("获取CP[".$this->str_source_id."]配置[message_ftp_import_file_url]，FTP地址未配置", $this->str_source_id);
            return \m_config::return_data(NS_CDS_FAIL,"获取CP[".$this->str_source_id."]配置[message_ftp_import_file_url]，FTP地址未配置");
        }
        $ftp = $arr_source_config['data_info']['nns_config']['message_ftp_import_file_url'];
        $ftp_arr = parse_url($ftp);
        if(!is_array($ftp_arr) || empty($ftp_arr['host']) || empty($ftp_arr['user']) || empty($ftp_arr['pass']))
        {
            \m_config::write_message_receive_log("获取CP[".$this->str_source_id."]配置[message_ftp_import_file_url]，FTP地址配置错误：".$ftp, $this->str_source_id);
            return \m_config::return_data(NS_CDS_FAIL,"获取CP[".$this->str_source_id."]配置[message_ftp_import_file_url]，FTP地址配置错误：".$ftp);
        }
        /*************扫描FTP获取文件*************/
        $port = !isset($ftp_arr['port']) ? '21' : $ftp_arr['port'];
        $path = !isset($ftp_arr['path']) ? '.' : $ftp_arr['path'];
        $ftp = new nns_ftp($ftp_arr['host'], $ftp_arr['user'], $ftp_arr['pass'], $port);
        $ftpcon = $ftp->connect(10, $this->passive);

        \m_config::write_message_receive_log("连接FTP地址端口为:{$ftp_arr['host']}:{$port},账号密码为：{$ftp_arr['user']}/{$ftp_arr['pass']}", $this->str_source_id);

        if (empty($ftpcon))//ftp链接失败
        {
            \m_config::write_message_receive_log("FTP链接失败", $this->str_source_id);
            return \m_config::return_data(NS_CDS_FAIL,"FTP链接失败");
        }
        //查看目录文件
        $list_file = $ftp->list_dir($path);
        if(empty($list_file['files']))
        {
            \m_config::write_message_receive_log("FTP目录没有文件列表", $this->str_source_id);
            return \m_config::return_data(NS_CDS_FAIL,"FTP目录没有文件列表");
        }
        $file_ex = isset($arr_source_config['data_info']['nns_config']['message_ftp_import_file_ex']) && !empty($arr_source_config['data_info']['nns_config']['message_ftp_import_file_ex']) ? $arr_source_config['data_info']['nns_config']['message_ftp_import_file_ex'] : 'xml';
        foreach ($list_file['files'] as $key=>$item)
        {
            //过滤非XML文件
            if (stripos($item['name'], "." . $file_ex) === FALSE) continue;

            $save_path = dirname(__FILE__) . '/' . $item['name'];
            $path_parts = pathinfo($save_path);
            if (!is_dir($path_parts['dirname']))
            {
                @mkdir($path_parts['dirname'], 0777, true);
            }

            $ftp_down_path = rtrim($path, '/');
            $down_name = $ftp_down_path . '/' . $item['name'];
            $res = $ftp->get($down_name, $save_path);
            //没有下载成功跳出下载
            if (!$res)
            {
                \m_config::write_message_receive_log("下载FTP文件失败：".$down_name, $this->str_source_id);
                continue;
            }
            //读取并入库
            $contents = file_get_contents($save_path);
            //删除本地文件
            @unlink($save_path);
            //组装消息入库信息
            list ( $usec, $sec ) = explode ( ' ', microtime () );
            $time = str_pad(intval(substr($usec, 2, 4)),4,'0',STR_PAD_LEFT);
            $micro_time = date('YmdHis', time()) . $time;
            $this->arr_in_message['base_info']['nns_message_time'] = $micro_time;
            $this->arr_in_message['base_info']['nns_message_id'] = np_guid_rand();
            $this->arr_in_message['base_info']['nns_cp_id'] = $this->str_source_id;
            $this->arr_in_message['base_info']['nns_message_content'] = $contents;
            //解析contents获取类型
            $this->parse_xml($contents);
            //入库消息队列
            $result_message = $this->push($this->arr_in_message);
            if($result_message['ret'] != NS_CDS_SUCCE)
            {
                \m_config::write_message_receive_log("入库消息失败:".var_export($result_message,true)."入库内容为：".var_export($this->arr_in_message,true), $this->str_source_id);
                continue;
            }
            //下载成功则删除FTP上文件
            $del_res = $ftp->delete($down_name);
            \m_config::write_message_receive_log("处理完消息后，删除FTP上内容：".var_export($del_res,true), $this->str_source_id);
        }
        \m_config::write_message_receive_log("-----------消息接收结束-----------",$this->str_source_id);
        return ;
    }

    /**
     * 获取媒资类型与操作类型
     * @param $contents
     */
    private function parse_xml($contents)
    {
        //解析下载的XML
        $dom = new DOMDocument('1.0', 'utf-8');
        $dom->loadXML($contents);
        $xml = $dom->saveXML();
        $xml_arr = np_xml2array::getArrayData($xml);//ret 0失败  1成功
        if ($xml_arr["ret"] != NS_CDS_FAIL)
        {
            \m_config::write_message_receive_log("解析得到的XML工单错误",$this->str_source_id);
            return;
        }
        foreach ($xml_arr['data']['children'] as $v)
        {
            if ($v['name'] == 'Objects')
            {
                $objects = $v['children'];
                continue;
            }
        }
        //取其中一个object作为type
        switch ($objects[0]['attributes']['ElementType'])
        {
            case 'Series':
                $this->arr_in_message['base_info']['nns_type'] = 4;
                break;
            case 'Program':
                $this->arr_in_message['base_info']['nns_type'] = 5;
                break;
            case 'Movie':
                $this->arr_in_message['base_info']['nns_type'] = 6;
                break;
        }

        switch ($objects[0]['attributes']['Action'])
        {
            case 'DELETE':
                $this->arr_in_message['base_info']['nns_action'] = 3;
                break;
            default:
                $this->arr_in_message['base_info']['nns_action'] = 1;
                break;
        }
        return;
    }
}

/**
 * Class ftp_import 定时任务控制
 */
class ftp_import extends m_timer
{
    public function action($params = null)
    {
        \m_config::timer_write_log($this->timer_path,'开始执行...',$this->child_path);
        $import = new import();
        $import -> import();
        \m_config::timer_write_log($this->timer_path,'执行结束...',$this->child_path);
    }
}

$ftp_import_timer = new ftp_import(\m_config::return_child_path(__FILE__,'ns_api'),'','','',__FILE__);
$ftp_import_timer->run();